﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Progresoft.Scheduler.RemoteInterface.Api;
using Progresoft.Scheduler.RemoteInterface.DataAccess;
using System.Globalization;
using System.Collections.Generic;

public partial class EditSchedule : System.Web.UI.Page
{
	/// <summary>
	/// ID задачи
	/// </summary>
	protected string Task
	{
		get
		{
			return Request["task"];
		}
	}

	/// <summary>
	/// ID запуска(если для edit)
	/// </summary>
	protected int? ScheduleID
	{
		get
		{
			int id = -1;
			if (int.TryParse(Request["schedule"], out id))
				return id;
			else
				return null;
		}
	}

	/// <summary>
	/// Система
	/// </summary>
	protected string System
	{
		get
		{
			return Request.QueryString["system"] == null ?
				string.Empty : this.Request.QueryString["system"].ToString();
		}
	}

	/// <summary>
	/// Откуда пришли на страницу
	/// </summary>
	protected string BackUrl
	{
		get
		{
			return ViewState["backUrl"] != null ?
				(string)ViewState["backUrl"] :
				"~/Dashboard.aspx";
		}
		set
		{
			ViewState["backUrl"] = value;
		}
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			// чтобы вернуться откуда пришли
			if (Request.UrlReferrer != null)
				BackUrl = Request.UrlReferrer.PathAndQuery;
			if (string.IsNullOrEmpty(this.System))
				throw new Exception("Не задан обязательный параметр system");
			if (string.IsNullOrEmpty(Task) && !ScheduleID.HasValue)
				throw new Exception("не указан обязательный параметр task");
			//заполняем данные по schedule, если задан его ID
			
			string serverUrl = ConnectorManager.GetServerUrl(this.System);
			Connector connector = ConnectorManager.GetConnector();
			SchedulerServer server = connector.GetServer(serverUrl);

			if (ScheduleID.HasValue)
			{
				TaskSchedule schedule = server.GetTaskScheduleByID(ScheduleID.Value);
				if (schedule == null)
					throw new Exception(string.Format("расписания с ID {0} не найдено", ScheduleID));
				txName.Text = schedule.Name;
				txExecHour.Text = schedule.ExecutionTime.Hour.ToString();
				txExecMinute.Text = schedule.ExecutionTime.Minute.ToString();
				LoadScheduleTypeNames((int)schedule.ScheduleType);
				if (schedule.ScheduleType == TaskScheduleType.EveryWeek)
					LoadWeekDayNames((int)schedule.ExecutionDayOfWeek);
				if (schedule.ScheduleType == TaskScheduleType.EveryMonth)
				{
					rblIsMonthBegin.SelectedIndex = schedule.ExecutionDayIsMonthBegin.Value ? 0 : 1;
					txtExecutionDayNumber.Text = schedule.ExecutionDayNumber.Value.ToString();
				}
				ddlLifeTime.SelectedValue = schedule.LifeTime.ToString();
			}
			else
			{
				LoadScheduleTypeNames(null);
				LoadWeekDayNames(null);
			}
			TaskScheduleType selectedType = (TaskScheduleType)Convert.ToInt32(ddlType.SelectedValue);
			pnlEveryWeek.Visible = selectedType == TaskScheduleType.EveryWeek;
			pnlEveryMonth.Visible = selectedType == TaskScheduleType.EveryMonth;
		}
	}

	/// <summary>
	/// Заполняем ДропДаун значениями из Enum с названиями
	/// типов расписаний
	/// </summary>
	protected void LoadScheduleTypeNames(int? selectedValue)
	{
		ddlType.DataBind();
		if (selectedValue != null)
			ddlType.SelectedValue = selectedValue.ToString();
	}

	/// <summary>
	/// Заполняем ДропДаун значениями из Enum с 
	/// короткими названиями дней
	/// </summary>
	/// <param name="selectedValue">Значение, которое будет установлено как выбранное в ДропДауне</param>
	protected void LoadWeekDayNames(int? selectedValue)
	{
		string[] days = ((DateTimeFormatInfo)new CultureInfo("ru-RU").DateTimeFormat).AbbreviatedDayNames;
		//чтобы "вс" было в конце
		List<DictionaryEntry> dataSource = new List<DictionaryEntry>();
		for (int i = 1; i < days.Length; i++)
			dataSource.Add(new DictionaryEntry(i.ToString(), days[i]));
		dataSource.Add(new DictionaryEntry("0", days[0]));
		ddlDayOfWeek.DataSource = dataSource;
		ddlDayOfWeek.DataBind();
		if (selectedValue.HasValue)
			ddlDayOfWeek.SelectedValue = selectedValue.Value.ToString();
	}

	protected void btnSave_Click(object sender, EventArgs e)
	{
		SaveSchedule();
		Response.Redirect(BackUrl);
	}

	protected void btnCancel_Click(object sender, EventArgs e)
	{
		Response.Redirect(BackUrl);
	}

	protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
	{
		TaskScheduleType selectedType = (TaskScheduleType)Convert.ToInt32(ddlType.SelectedValue);
		switch (selectedType)
		{
			case TaskScheduleType.EveryWeek:
				LoadWeekDayNames(null);
				break;
			case TaskScheduleType.EveryMonth:
				rblIsMonthBegin.SelectedIndex = 0;
				txtExecutionDayNumber.Text = string.Empty;
				break;
		}
		pnlEveryWeek.Visible = selectedType == TaskScheduleType.EveryWeek;
		pnlEveryMonth.Visible = selectedType == TaskScheduleType.EveryMonth;
	}

	private void SaveSchedule()
	{
		TaskSchedule ts = new TaskSchedule();
		if (string.IsNullOrEmpty(Task) && !ScheduleID.HasValue)
			throw new Exception("Не определена задача, к которой относится расписание.\r\n Изменения не будут сохранены.");
		ts.Name = txName.Text;
		ts.ScheduleType = (TaskScheduleType)Enum.Parse(typeof(TaskScheduleType), ddlType.SelectedValue);
		ts.LifeTime = Convert.ToInt32(ddlLifeTime.SelectedValue);
		try
		{
			ts.ExecutionTime = Convert.ToDateTime(string.Format("1900-01-01 {0}:{1}:00", txExecHour.Text, txExecMinute.Text));
		}
		catch (System.FormatException)
		{
			throw new Exception(
				"Неверный формат времени.\r\n " +
				string.Format("{0}:{1}:00", txExecHour.Text, txExecMinute.Text));
		}
		if (ts.ScheduleType == TaskScheduleType.EveryWeek)
			ts.ExecutionDayOfWeek = (DayOfWeek)Convert.ToInt32(ddlDayOfWeek.SelectedValue);
		if (ts.ScheduleType == TaskScheduleType.EveryMonth)
		{
			ts.ExecutionDayIsMonthBegin = (rblIsMonthBegin.SelectedIndex == 0);
			ts.ExecutionDayNumber = Convert.ToInt32(txtExecutionDayNumber.Text);
			if (!(bool)ts.ExecutionDayIsMonthBegin && (ts.ExecutionDayNumber > 28))
				throw new Exception("Если расчет идет от конца месяца, то число дней не должно превышать 28.");
		}

		string serverUrl = ConnectorManager.GetServerUrl(this.System);
		Connector connector = ConnectorManager.GetConnector();
		SchedulerServer server = connector.GetServer(serverUrl);

		server.SaveSchedule(System, Task, ts);
	}

}
